<template>
  <div class="contentBox gl_heightFull">
    <div class="dataLeft">
      <div class="operation">
        <div class="timer">
          <div class="chooseTime">
            <div :class="activeIndex === 0 ? 'activeTime' : ''" @click="changeTime(0)">今日</div>
            <div :class="activeIndex === 1 ? 'activeTime' : ''" @click="changeTime(1)">本周</div>
            <div :class="activeIndex === 2 ? 'activeTime' : ''" @click="changeTime(2)">本月</div>
          </div>
        </div>
        <el-tabs v-model="activeData" class="tabList">
          <el-tab-pane label="整体运营情况" class="allData gl_clear" name="allData">
            <allData v-if="activeData === 'allData'" ref="allData" :active-time="activeIndex" />
          </el-tab-pane>
          <el-tab-pane label="机构运营数据" class="allData gl_clear" name="oneData">
            <oneData v-if="activeData === 'oneData'" ref="oneData" :active-time="activeIndex" />
          </el-tab-pane>
        </el-tabs>
      </div>
      <div id="echarts">
        <el-date-picker
          v-model="timer"
          class="datePicker"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          size="mini"
          :clearable="false"
          @change="handleTimeChange"
        />
        <div class="chartTitle">销售额趋势</div>
        <BarChart ref="barChart" :loading="chartLoading" :default-data="salesData" :height="echartsHeight" :width="echartsWidth" />
      </div>
    </div>
    <div class="dataRight">
      <div class="quickOperation">在线客服</div>
      <div class="quickOperation">操作手册<span class="prompt">操作手册，用于对系统的了解，查找流程等功能</span></div>
      <div class="toDo">
        <el-tabs v-model="activeEvents" v-loading="todoLoading" class="tabEvents">
          <el-tab-pane label="待办事项" name="events">
            <div class="oneEvents">
              <el-button size="medium" type="danger" @click="goToDetail('renewal')">续费提醒</el-button>
              <span class="content">有 {{ toDoList.warningCount !== null ? toDoList.warningCount : '--' }} 位学员的课时已到预警线</span>
            </div>
            <div class="oneEvents">
              <el-button size="medium" type="warning" @click="goToDetail('followUp')">跟进提醒</el-button>
              <span class="content">有 {{ toDoList.followingUpCount !== null ? toDoList.followingUpCount : '--' }} 位学员需要跟进</span>
            </div>
            <div class="oneEvents">
              <el-button size="medium" type="primary" @click="goToDetail('allocation')">分配提醒</el-button>
              <span class="content">有 {{ toDoList.unassignedCount !== null ? toDoList.unassignedCount : '--' }} 位学员待分配班级</span>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>
import BarChart from './BarChart';
import allData from './allData';
import oneData from './oneData';
import { mapState } from 'vuex';
import { CopyData } from '@/lib';
import {
  api_GET_ClubWorkBenchToDoItemData, // 查询待办事项数据
  api_GET_ClubWorkBenchSalesAmountStatistics // 获取销售趋势统计数据
} from '@/extend/api/hall.js';
export default {
  components: {
    BarChart, allData, oneData
  },
  data() {
    return {
      timer: [],
      activeData: 'allData',
      echartsWidth: '1093px',
      echartsHeight: '370px',
      activeEvents: 'events',
      activeIndex: 0,
      salesData: {
        // title: {
        //   text: '销售额趋势',
        //   top: '15px',
        //   left: '20px',
        //   textStyle: {
        //     color: '#333',
        //     fontWeight: 'bold',
        //     fontSize: 14
        //   }
        // },
        grid: {
          left: '70px',
          right: '40px',
          top: '75px',
          bottom: '40px'
        },
        tooltip: { // 提示框
          trigger: 'axis',
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: 'cross' // 默认为直线，可选为：'line' | 'shadow'
          },
          backgroundColor: 'rgba(0, 0, 0, .75)',
          textStyle: {
            color: '#fff',
            align: 'left'
          },
          extraCssText: 'box-shadow: 0px 2px 10px 0px rgba(0,0,0,0.15)',
          padding: [8, 16],
          borderRadius: 3
        },
        xAxis: {
          type: 'category',
          data: [],
          boundaryGap: false,
          axisLine: { // 坐标轴线
            lineStyle: {
              color: '#D9D9D9'
            }
          },
          axisTick: { // 坐标轴刻度
            alignWithLabel: true // 刻度与标签对齐
          },
          axisLabel: { // 刻度标签
            color: '#595959',
            formatter: function (value) {
              return value.substring(5, 10);
            }
          }
        },
        yAxis: {
          name: '销售金额（元）',
          nameTextStyle: {
            padding: [0, 0, 0, -3],
            color: '#464646'
          },
          axisLine: { // 坐标轴线
            show: false,
            lineStyle: {
              color: '#595959'
            }
          },
          axisTick: { // 坐标轴刻度
            show: false
          },
          splitLine: { // grid分隔线
            show: true,
            lineStyle: {
              type: 'dashed',
              color: ['#E8E8E8']
            }
          },
          splitArea: { // grid分隔区域
            show: false
          }
        },
        series: [
          {
            name: '销售金额',
            data: [],
            type: 'line',
            itemStyle: {
              normal: {
                color: '#2FC25B', // 折线的颜色
                lineStyle: {
                  color: '#2fc25b',
                  width: 2
                }
              }
            },
            smooth: false
          }
        ]
      },
      toDoList: {
        followingUpCount: null,
        unassignedCount: null,
        warningCount: null
      },
      chartQO: {
        organizationUnitId: '',
        StartDate: null,
        EndDate: null
      },
      chartLoading: false,
      todoLoading: false
    };
  },
  computed: {
    ...mapState({
      info: state => state.user.info,
      currentUserType: state => state.user.currentUserType
    })
  },
  mounted() {
    const that = this;
    window.addEventListener('resize', function() {
      that.echartsWidth = window.getComputedStyle(document.getElementById('echarts')).width;
      that.echartsHeight = window.getComputedStyle(document.getElementById('echarts')).height;
      that.$refs.barChart ? that.$refs.barChart.resizeChart() : '';
    });
    this.$nextTick(() => {
      that.echartsWidth = window.getComputedStyle(document.getElementById('echarts')).width;
      that.echartsHeight = window.getComputedStyle(document.getElementById('echarts')).height;
    });
    this.initEchart();
    this.getToDoList();
  },
  methods: {
    // 修改运营数据查询时间
    changeTime(index) {
      this.activeIndex = index;
    },
    handleTimeChange(time) {
      this.chartQO.StartDate = time && time[0] + ' 00:00:00';
      this.chartQO.EndDate = time && time[1] + ' 23:59:59';
      this.getChartData();
    },
    initEchart() {
      const day1 = this.handleDate(-30, '-') + ' 00:00:00';
      const day2 = this.handleDate(0, '-') + ' 23:59:59';
      this.timer = [day1, day2];
      this.chartQO.StartDate = day1;
      this.chartQO.EndDate = day2;
      this.getChartData();
    },
    getChartData() {
      this.chartLoading = true;
      this.chartQO.organizationUnitId = this.currentUserType && this.currentUserType.organizationUnitId;
      api_GET_ClubWorkBenchSalesAmountStatistics(this.chartQO).then(res => {
        this.chartLoading = false;
        const orderAmount = res || [];
        const amount = this.handleEChartsData(orderAmount);
        this.salesData.xAxis.data = amount.xAxis;
        this.salesData.series[0].data = amount.yAxis;
      }, error => {
        this.chartLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    handleEChartsData(data) {
      const obj = {
        xAxis: [],
        yAxis: []
      };
      for (var i = 0; i < data.length; i++) {
        var item = data[i];
        item.dateTime = item.dateTime.substring(0, 4) + '.' + item.dateTime.substring(5, 7) + '.' + item.dateTime.substring(8, 10) + '';
        obj.xAxis.push(item.dateTime);
        const amount = this.formatMoney(item.amount);
        obj.yAxis.push(amount);
      }
      return obj;
    },
    // 获取待办事项
    getToDoList() {
      this.todoLoading = true;
      api_GET_ClubWorkBenchToDoItemData().then(res => {
        this.todoLoading = false;
        CopyData(res, this.toDoList);
      }, error => {
        this.todoLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 处理初始的统计时间
    handleDate (num, str) {
      var today = new Date();
      var nowTime = today.getTime();
      var ms = 24 * 3600 * 1000 * num;
      today.setTime(parseInt(nowTime + ms));
      var oYear = today.getFullYear();
      var oMoth = (today.getMonth() + 1).toString();
      if (oMoth.length <= 1) oMoth = '0' + oMoth;
      var oDay = today.getDate().toString();
      if (oDay.length <= 1) oDay = '0' + oDay;
      return oYear + str + oMoth + str + oDay;
    },
    goToDetail(code) {
      switch (code) {
        case 'renewal':
          this.$router.push({ name: 'EarlyWarning' });
          break;
        case 'followUp':
          this.$router.push({ name: 'Crm' });
          break;
        case 'allocation':
          this.$router.push({
            name: 'StudentList',
            query: { classId: 'empty' }
          });
          break;
      }
    },
    // 获取静态图片
    getStaticFileUrl(relativeUrl) {
      if (relativeUrl) {
        return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
      } else {
        return require('@/assets/images/face_default.png');
      }
    },
    // 格式化货币格式 （分）
    formatMoney(num) {
      if (typeof num === 'number' && !Number.isNaN(num)) {
        // num 是数字类型 且不是 NaN
        let strNum = String(num); // 金额文本类型
        if (num >= 0) {
          strNum = strNum.padStart(3, '0'); // 用0填充保证最小三位数
          return strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        } else {
          const _mark = strNum.slice(0, 1); // 负号
          const _noMark = strNum.slice(1); // 无负号数值
          strNum = _noMark.padStart(3, '0'); // 用0填充保证最小三位数
          return _mark + strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        }
      } else {
        return '';
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.contentBox {
  width: 100%;
  position: relative;
  font-family: PingFang SC, PingFang SC-Regular;
  display: flex;
  justify-content: space-between;
  align-content: center;
  overflow: auto;
}
.dataLeft {
  min-width: 800px;
  width: 64%;
  .operation {
    background: white;
    border-radius: 2px;
    position: relative;
    height: 300px;
    margin-bottom: 20px;
    .timer {
      position: absolute;
      z-index: 100 !important;
      top: 0px;
      right: 30px;
      .chooseTime {
        cursor: pointer;
        width: 120px;
        height: 48px;
        line-height: 48px;
        display: flex;
        color: #979797;
        font-size: 14px;
        font-weight: 400;
        justify-content: space-between;
        .activeTime {
          color: #1890FF;
        }
      }
    }
    .tabList {
      padding: 5px 15px 0px 15px;
      .allData {
        padding: 20px 0px 0px 0px;
      }
    }
  }
  #echarts {
    min-height: 350px;
    height: calc(100vh - 460px);
    padding: 0px;
    background: white;
    border-radius: 2px;
    position: relative;
    .datePicker {
      width: 260px;
      position: absolute;
      z-index: 100 !important;
      top: 20px;
      right: 30px;
    }
  }
}
.dataRight {
  min-width: 425px;
  width: 36%;
  padding-left: 20px;
  .quickOperation {
    width: 100%;
    height: 68px;
    margin-bottom: 20px;
    box-sizing: border-box;
    padding-left: 20px;
    line-height: 68px;
    background: white;
    font-size: 20px;
    font-weight: 400;
    border-radius: 2px;
    overflow: hidden;
    .prompt {
      color: #979797;
      font-size: 14px;
      font-weight: normal;
      margin-left: 10px;
    }
  }
  .toDo {
    min-height: 494px;
    height: calc(100vh - 316px);
    background: white;
    .tabEvents {
      padding: 5px 15px 0px 15px;
      .oneEvents {
        height: 55px;
        line-height: 55px;
        color: white;
        .content {
          font-size: 14px;
          font-weight: 400;
          color: #333;
          margin-left: 10px;
        }
      }
    }
  }
}
.chartTitle {
  position: absolute;
  display: inline-block;
  width: auto;
  font-weight: bold;
  height: 30px;
  line-height: 30px;
  top: 15px;
  left: 20px;
  font-size: 18px;
}
</style>
